package com.nmc.service.dao.impl;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.nmc.service.dao.UserDao;
import com.nmc.service.model.User;

/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve User objects.
 *
*/
public class UserDaoImpl extends GenericDaoImpl<User, Long> implements UserDao, UserDetailsService {

    public UserDaoImpl(Class<User> persistentClass,
			SessionFactory sessionFactory) {
		super(persistentClass, sessionFactory);
		// TODO Auto-generated constructor stub
	}

	public UserDaoImpl(Class<User> persistentClass) {
		super(persistentClass);
		// TODO Auto-generated constructor stub
	}

	/**
     * Constructor that sets the entity to User.class.
     */
    public UserDaoImpl() {
        super(User.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        return getHibernateTemplate().find("from User u order by upper(u.username)");
    }

    /**
     * {@inheritDoc}
     */
    public User saveUser(User user) {
        if (log.isDebugEnabled()) {
            log.debug("user's id: " + user.getId());
        }
        getHibernateTemplate().saveOrUpdate(user);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return user;
    }

    /**
     * Overridden simply to call the saveUser method. This is happenening 
     * because saveUser flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public User save(User user) {
        return this.saveUser(user);
    }

    /** 
     * {@inheritDoc}
    */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("loadUserByUsername -- userName "+username);
    	List users = getHibernateTemplate().find("from User where username=?", username);
        log.debug("userList "+users);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
    }

    /** 
     * {@inheritDoc}
    */
    public String getUserPassword(String username) {
        SimpleJdbcTemplate jdbcTemplate =
                new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
       ;
        return jdbcTemplate.queryForObject(
                "select password from user where username=?", String.class, username);

    }
    
    public List<User> searchUsers(String searchStr) {
    	List<User> usersList = null;
    	Query query = getSession().createSQLQuery("select * from user where first_name like '%"+searchStr+"%' or last_name like '%"+searchStr+"%'").addEntity(User.class);
    	usersList = query.list();
    	return usersList;
    }
    
    public List<User> getUsersOfUserType(String userType) {
    	List<User> usersList = null;
    	Query query = getSession().createSQLQuery("select * from user where user_type='" + userType + "'").addEntity(User.class);
    	usersList = query.list();
    	return usersList;
    }
    
}
